package com.xujie.sportsmeeting.controller;

import com.xujie.sportsmeeting.common.result.Result;
import com.xujie.sportsmeeting.dto.LoginDTO;
import com.xujie.sportsmeeting.dto.RegisterDTO;
import com.xujie.sportsmeeting.dto.ChangePasswordDTO;
import com.xujie.sportsmeeting.entity.SysUser;
import com.xujie.sportsmeeting.service.SysUserService;
import com.xujie.sportsmeeting.vo.UserInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证控制器
 */
@Tag(name = "认证管理", description = "用户登录、注册、权限相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final SysUserService sysUserService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = sysUserService.login(loginDTO.getUsername(), loginDTO.getPassword());
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("tokenType", "Bearer");
        
        return Result.success("登录成功", result);
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterDTO registerDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(registerDTO, user);
        
        sysUserService.register(user);
        return Result.success("注册成功");
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/userinfo")
    public Result<UserInfoVO> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        SysUser user = sysUserService.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        
        // 查询用户角色和权限
        List<String> roles = sysUserService.findRolesByUserId(user.getId());
        List<String> permissions = sysUserService.findPermissionsByUserId(user.getId());
        
        userInfoVO.setRoles(roles);
        userInfoVO.setPermissions(permissions);
        
        return Result.success(userInfoVO);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/changePassword")
    public Result<Void> changePassword(@Valid @RequestBody ChangePasswordDTO changePasswordDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        SysUser user = sysUserService.findByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        sysUserService.changePassword(user.getId(), changePasswordDTO.getOldPassword(), changePasswordDTO.getNewPassword());
        return Result.success("密码修改成功");
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT是无状态的，客户端删除token即可
        return Result.success("退出成功");
    }
}
